﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using TireService.Data;
using System.Web.Security;

namespace TireService.Web.UserControls
{
    public partial class ucEditCustomerTireSet : System.Web.UI.UserControl
    {
        private string _controlname = "EditCustomerTireSet";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToBoolean(Session["UserControlLoaded" + _controlname]))
            {
                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();

                // Show customer tiresets
                LoadCustomerTireSet(Convert.ToInt32(Session["CustomerId" + _controlname]), db);
            }
        }

        protected void callbackEditCustomerTireSetPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            Session["CustomerId" + _controlname] = Convert.ToInt32(e.Parameter);
            
            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int CustomerId)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            if (CustomerId != 0)
            {
                // Show customer cars
                LoadCustomerTireSet(CustomerId, db);
            }
            else
            {
                // Error
                throw new ArgumentException("Kunde ikke fundet");
            }

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind tireset data to gridview
        /// </summary>
        /// <param name="CustomerId">Id on customer</param>
        /// <param name="db">Connection to database</param>
        private void LoadCustomerTireSet(int CustomerId, TireServiceDB db)
        {
            //gvTireSet.DataSource = db.GetCarTireSetViews(CustomerId);
            gvTireSet.DataSource = db.GetCustomerTireSets(CustomerId, cbShowChildTireSets.Checked);
            gvTireSet.DataBind();

            // Prepare data for editmode of tireset 
            GridViewDataComboBoxColumn ddlTireType = gvTireSet.Columns["TireTypeDropdown"] as GridViewDataComboBoxColumn;
            ddlTireType.PropertiesComboBox.ValueType = typeof(int);
            ddlTireType.PropertiesComboBox.DataSource = db.GetTireType();
            ddlTireType.PropertiesComboBox.TextField = "Description";
            ddlTireType.PropertiesComboBox.ValueField = "TireTypeId";
            ddlTireType.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireType.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireSpeedIndex = gvTireSet.Columns["TireSpeedIndexDropdown"] as GridViewDataComboBoxColumn;
            ddlTireSpeedIndex.PropertiesComboBox.ValueType = typeof(int);
            ddlTireSpeedIndex.PropertiesComboBox.DataSource = db.GetTireSpeedIndex();
            ddlTireSpeedIndex.PropertiesComboBox.TextField = "Description";
            ddlTireSpeedIndex.PropertiesComboBox.ValueField = "TireSpeedIndexId";
            ddlTireSpeedIndex.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireSpeedIndex.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireLoadIndex = gvTireSet.Columns["TireLoadIndexDropdown"] as GridViewDataComboBoxColumn;
            ddlTireLoadIndex.PropertiesComboBox.ValueType = typeof(int);
            ddlTireLoadIndex.PropertiesComboBox.DataSource = db.GetTireLoadIndex();
            ddlTireLoadIndex.PropertiesComboBox.TextField = "Description";
            ddlTireLoadIndex.PropertiesComboBox.ValueField = "TireLoadIndexId";
            ddlTireLoadIndex.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireLoadIndex.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireBrand = gvTireSet.Columns["TireBrandDropdown"] as GridViewDataComboBoxColumn;
            ddlTireBrand.PropertiesComboBox.ValueType = typeof(int);
            ddlTireBrand.PropertiesComboBox.DataSource = db.GetTireBrands();
            ddlTireBrand.PropertiesComboBox.TextField = "Description";
            ddlTireBrand.PropertiesComboBox.ValueField = "TireBrandId";
            ddlTireBrand.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireBrand.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireSetStatus = gvTireSet.Columns["TireSetStatusDropdown"] as GridViewDataComboBoxColumn;
            ddlTireSetStatus.PropertiesComboBox.ValueType = typeof(int);
            ddlTireSetStatus.PropertiesComboBox.DataSource = db.GetTireSetStatus();
            ddlTireSetStatus.PropertiesComboBox.TextField = "Description";
            ddlTireSetStatus.PropertiesComboBox.ValueField = "TireSetStatusId";
            ddlTireSetStatus.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireSetStatus.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlSize = gvTireSet.Columns["SizeDropdown"] as GridViewDataComboBoxColumn;
            ddlSize.PropertiesComboBox.ValueType = typeof(decimal);
            ddlSize.PropertiesComboBox.Items.Add("8,0");
            ddlSize.PropertiesComboBox.Items.Add("9,0");
            ddlSize.PropertiesComboBox.Items.Add("10,0");
            ddlSize.PropertiesComboBox.Items.Add("12,0");
            ddlSize.PropertiesComboBox.Items.Add("13,0");
            ddlSize.PropertiesComboBox.Items.Add("14,0");
            ddlSize.PropertiesComboBox.Items.Add("15,0");
            ddlSize.PropertiesComboBox.Items.Add("16,0");
            ddlSize.PropertiesComboBox.Items.Add("17,0");
            ddlSize.PropertiesComboBox.Items.Add("17,5");
            ddlSize.PropertiesComboBox.Items.Add("18,0");
            ddlSize.PropertiesComboBox.Items.Add("19,0");
            ddlSize.PropertiesComboBox.Items.Add("20,0");
            ddlSize.PropertiesComboBox.Items.Add("21,0");
            ddlSize.PropertiesComboBox.Items.Add("22,0");
            ddlSize.PropertiesComboBox.Items.Add("23,0");
            ddlSize.PropertiesComboBox.Items.Add("24,0");
            ddlSize.PropertiesComboBox.Items.Add("48,0");
            ddlSize.PropertiesComboBox.Items.Add("390,0");
            ddlSize.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlSize.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlWidth = gvTireSet.Columns["WidthDropdown"] as GridViewDataComboBoxColumn;
            ddlWidth.PropertiesComboBox.ValueType = typeof(decimal);
            ddlWidth.PropertiesComboBox.Items.Add("125,0");
            ddlWidth.PropertiesComboBox.Items.Add("135,0");
            ddlWidth.PropertiesComboBox.Items.Add("140,0");
            ddlWidth.PropertiesComboBox.Items.Add("145,0");
            ddlWidth.PropertiesComboBox.Items.Add("155,0");
            ddlWidth.PropertiesComboBox.Items.Add("165,0");
            ddlWidth.PropertiesComboBox.Items.Add("175,0");
            ddlWidth.PropertiesComboBox.Items.Add("185,0");
            ddlWidth.PropertiesComboBox.Items.Add("195,0");
            ddlWidth.PropertiesComboBox.Items.Add("205,0");
            ddlWidth.PropertiesComboBox.Items.Add("215,0");
            ddlWidth.PropertiesComboBox.Items.Add("225,0");
            ddlWidth.PropertiesComboBox.Items.Add("230,0");
            ddlWidth.PropertiesComboBox.Items.Add("235,0");
            ddlWidth.PropertiesComboBox.Items.Add("245,0");
            ddlWidth.PropertiesComboBox.Items.Add("255,0");
            ddlWidth.PropertiesComboBox.Items.Add("265,0");
            ddlWidth.PropertiesComboBox.Items.Add("275,0");
            ddlWidth.PropertiesComboBox.Items.Add("285,0");
            ddlWidth.PropertiesComboBox.Items.Add("295,0");
            ddlWidth.PropertiesComboBox.Items.Add("305,0");
            ddlWidth.PropertiesComboBox.Items.Add("315,0");
            ddlWidth.PropertiesComboBox.Items.Add("325,0");
            ddlWidth.PropertiesComboBox.Items.Add("335,0");
            ddlWidth.PropertiesComboBox.Items.Add("345,0");
            ddlWidth.PropertiesComboBox.Items.Add("375,0");
            ddlWidth.PropertiesComboBox.Items.Add("600,0");
            ddlWidth.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlWidth.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlHeight = gvTireSet.Columns["HeightDropdown"] as GridViewDataComboBoxColumn;
            ddlHeight.PropertiesComboBox.ValueType = typeof(decimal);
            ddlHeight.PropertiesComboBox.Items.Add("25,0");
            ddlHeight.PropertiesComboBox.Items.Add("30,0");
            ddlHeight.PropertiesComboBox.Items.Add("35,0");
            ddlHeight.PropertiesComboBox.Items.Add("40,0");
            ddlHeight.PropertiesComboBox.Items.Add("45,0");
            ddlHeight.PropertiesComboBox.Items.Add("50,0");
            ddlHeight.PropertiesComboBox.Items.Add("55,0");
            ddlHeight.PropertiesComboBox.Items.Add("60,0");
            ddlHeight.PropertiesComboBox.Items.Add("65,0");
            ddlHeight.PropertiesComboBox.Items.Add("70,0");
            ddlHeight.PropertiesComboBox.Items.Add("75,0");
            ddlHeight.PropertiesComboBox.Items.Add("80,0");
            ddlHeight.PropertiesComboBox.Items.Add("85,0");
            ddlHeight.PropertiesComboBox.Items.Add("95,0");
            ddlHeight.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlHeight.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            gvTireSet.ClearSort();
            gvTireSet.GroupSummary.Clear();
            gvTireSet.GroupBy(gvTireSet.Columns["CarBrandDescription"]);
            gvTireSet.GroupBy(gvTireSet.Columns["Model"]);
            gvTireSet.ExpandAll();

            Session["UserControlLoaded" + _controlname] = true;
        }

        /// <summary>
        /// Postback function that updates gridview with tiresets
        /// </summary>
        protected void gvTireSet_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Show tiresets
            LoadCustomerTireSet(Convert.ToInt32(Session["CustomerId" + _controlname]), db);
        }

        /// <summary>
        /// Gridview function for updating customer tireset
        /// </summary>
        protected void gvTireSet_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (Convert.ToInt32(Session["CustomerId" + _controlname]) != 0)
            {
                if (e.NewValues["CarId"] == null)
                {
                    throw new ArgumentException("Bil skal oprettes/vælges før hjulsæt kan oprettes/redigeres.");
                }

                // Get id
                int TireSetId = Convert.ToInt32(e.Keys["TireSetId"]);

                TireServiceDB db = new TireServiceDB();

                TireSet tireset = new TireSet();

                // Instantiate business layer
                TireSetLogBLL bll = new TireSetLogBLL();

                // Fecth existing customer tireset
                tireset = db.GetTireSet(TireSetId);

                if (tireset != null)
                {
                    int fromtiresetstatus = tireset.TireSetStatusId;

                    tireset.CarId = Convert.ToInt32(e.NewValues["CarId"]);
                    tireset.TireTypeId = Convert.ToInt32(e.NewValues["TireTypeId"]);
                    tireset.Size = Convert.ToDecimal(e.NewValues["Size"]);
                    tireset.Width = Convert.ToDecimal(e.NewValues["Width"]);
                    tireset.Height = Convert.ToDecimal(e.NewValues["Height"]);
                    tireset.TireSpeedIndexId = Convert.ToInt32(e.NewValues["TireSpeedIndexId"]);
                    tireset.TireLoadIndexId = Convert.ToInt32(e.NewValues["TireLoadIndexId"]);
                    tireset.TireBrandId = Convert.ToInt32(e.NewValues["TireBrandId"]);
                    tireset.TireBrandNote = e.NewValues["TireBrandNote"].ToString();
                    tireset.LockingBolt = Convert.ToBoolean(e.NewValues["LockingBolt"]);
                    tireset.HubCaps = Convert.ToBoolean(e.NewValues["HubCaps"]);
                    tireset.RunFlatTire = Convert.ToBoolean(e.NewValues["RunFlatTire"]);
                    tireset.RimProtection = Convert.ToBoolean(e.NewValues["RimProtection"]);
                    tireset.ExtraBolts = Convert.ToBoolean(e.NewValues["ExtraBolts"]);
                    tireset.ManufactureDate = Convert.ToDateTime(e.NewValues["ManufactureDate"]);
                    tireset.TireSetStatusId = Convert.ToInt32(e.NewValues["TireSetStatusId"]);
                    tireset.SocketWrenchSize = Convert.ToInt32(e.NewValues["SocketWrenchSize"]);

                    // Create tireset log
                    bll.CreateTireSetLog(db, tireset, DateTime.Now, fromtiresetstatus, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), null, null, null, null, null, tireset.ContainerCargoRoomId);
                }
                else
                {
                    // Customer subscription does not exists
                    throw new ArgumentException("Hjulsæt eksistere ikke");
                }

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvTireSet.CancelEdit();

                // Reset edit mode
                TireSetId = 0;

                // Refresh gridview
                LoadCustomerTireSet(Convert.ToInt32(Session["CustomerId" + _controlname]), db);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - hjulsæt kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for creating customer tireset
        /// </summary>
        protected void gvTireSet_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            if (Convert.ToInt32(Session["CustomerId" + _controlname]) != 0)
            {
                // Set id
                int TireSetId = 0;

                TireServiceDB db = new TireServiceDB();

                TireSet tireset = new TireSet();

                // Instantiate business layer
                TireSetLogBLL bll = new TireSetLogBLL();

                // Create new tireset
                tireset.CarId = Convert.ToInt32(e.NewValues["CarId"]);
                tireset.TireTypeId = Convert.ToInt32(e.NewValues["TireTypeId"]);
                tireset.Size = Convert.ToDecimal(e.NewValues["Size"]);
                tireset.Width = Convert.ToDecimal(e.NewValues["Width"]);
                tireset.Height = Convert.ToDecimal(e.NewValues["Height"]);
                tireset.TireSpeedIndexId = Convert.ToInt32(e.NewValues["TireSpeedIndexId"]);
                tireset.TireLoadIndexId = Convert.ToInt32(e.NewValues["TireLoadIndexId"]);
                tireset.TireBrandId = Convert.ToInt32(e.NewValues["TireBrandId"]);
                tireset.TireBrandNote = e.NewValues["TireBrandNote"].ToString();
                tireset.LockingBolt = Convert.ToBoolean(e.NewValues["LockingBolt"]);
                tireset.HubCaps = Convert.ToBoolean(e.NewValues["HubCaps"]);
                tireset.RunFlatTire = Convert.ToBoolean(e.NewValues["RunFlatTire"]);
                tireset.RimProtection = Convert.ToBoolean(e.NewValues["RimProtection"]);
                tireset.ExtraBolts = Convert.ToBoolean(e.NewValues["ExtraBolts"]);
                tireset.ManufactureDate = Convert.ToDateTime(e.NewValues["ManufactureDate"]);
                tireset.TireSetStatusId = Convert.ToInt32(e.NewValues["TireSetStatusId"]);
                tireset.SocketWrenchSize = Convert.ToInt32(e.NewValues["SocketWrenchSize"]);

                // Add to database
                db.AddTireSet(tireset);

                // Create tireset log
                bll.CreateTireSetLog(db, tireset, DateTime.Now, null, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), null, null, null, null, null, tireset.ContainerCargoRoomId);

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvTireSet.CancelEdit();

                // Reset edit mode
                TireSetId = 0;

                // Refresh gridview
                LoadCustomerTireSet(Convert.ToInt32(Session["CustomerId" + _controlname]), db);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - hjulsæt kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }
    }
}